#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iostream>

// 地球半径（米）
const double EARTH_RADIUS = 6371000.0;

// 将度转换为弧度
double degreesToRadians(double degrees) { return degrees * M_PI / 180.0; }

// 将弧度转换为度
double radiansToDegrees(double radians) { return radians * 180.0 / M_PI; }

// 生成给定范围内的随机浮点数
double randomDouble(double min, double max) {
  return min + static_cast<double>(rand()) / (static_cast<double>(RAND_MAX / (max - min)));
}

// 计算两点间的距离（米）
double haversineDistance(double lat1, double lon1, double lat2, double lon2) {
  lat1 = degreesToRadians(lat1);
  lon1 = degreesToRadians(lon1);
  lat2 = degreesToRadians(lat2);
  lon2 = degreesToRadians(lon2);

  double dLat = lat2 - lat1;
  double dLon = lon2 - lon1;

  double a = sin(dLat / 2) * sin(dLat / 2) + cos(lat1) * cos(lat2) * sin(dLon / 2) * sin(dLon / 2);
  double c = 2 * atan2(sqrt(a), sqrt(1 - a));

  return EARTH_RADIUS * c;
}

// 在给定初始经纬度和半径内生成随机经纬度
void generateRandomPoint(double initialLat, double initialLon, double radius, double& randomLat, double& randomLon) {
  // 为随机数生成器设置种子
  srand(static_cast<unsigned>(time(0)));

  // 尝试多次直到找到一个合适的点
  for (int attempt = 0; attempt < 1000; ++attempt) {
    double angle = randomDouble(0, 2 * M_PI);
    double distance = randomDouble(0, radius);

    double newLat = initialLat + (distance / EARTH_RADIUS) * cos(angle);
    double newLon = initialLon + (distance / (EARTH_RADIUS * cos(degreesToRadians(initialLat)))) * sin(angle);

    // 确保新点不超过经纬度范围
    if (newLat >= -90 && newLat <= 90 && newLon >= -180 && newLon <= 180) {
      double calculatedDistance = haversineDistance(initialLat, initialLon, newLat, newLon);
      if (fabs(calculatedDistance - distance) <= 1.0) {  // 允许微小误差
        randomLat = newLat;
        randomLon = newLon;
        return;
      }
    }
  }

  // 如果多次尝试都失败，则简单地返回初始点加上微小的随机偏移量（虽然这不一定在指定半径内）
  randomLat = initialLat + (randomDouble(-1, 1) * (radius / 10000.0));
  randomLon = initialLon + (randomDouble(-1, 1) * (radius / (10000.0 * cos(degreesToRadians(initialLat)))));
}

int main() {
  double initialLat = 30.424721;   // 示例初始纬度
  double initialLon = 114.417496;  // 示例初始经度
  double radius = 100.0;         // 半径100米

  double randomLat, randomLon;
  generateRandomPoint(initialLat, initialLon, radius, randomLat, randomLon);

  std::cout << "Random Latitude: " << randomLat << std::endl;
  std::cout << "Random Longitude: " << randomLon << std::endl;

  return 0;
}